package com.maisonliberte.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

import com.maisonliberte.enums.ImageSizeEnum;


public class ImageUtil {

	public static boolean resizeImage(String src, String tar, ImageSizeEnum size){

		//MIDDEL_250px,
		//SMALL_80px,
		//LIST_150px,
		//DISPLAY_120px,
		
		
		try{
			File orgImageFile = new File(src);
			BufferedImage orgImage = ImageIO.read(orgImageFile);
			int width = 0;
			
			switch(size){
			case MIDDLE_250px :
				width = 250;
				break;
			case LIST_150px:
				width = 150;
				break;
			case DISPLAY_120px:
				width = 120;
				break;
			case SMALL_80px:
				width = 80;
				break;
			default:
				width = 80;
				break;
			}
			
			int height = (int)(((double)width / orgImage.getWidth()) * (double)orgImage.getHeight());

			BufferedImage resizeImage = new BufferedImage(width, height, orgImage.getType());
	// ここからリサイズ処理
//			AffineTransformOp ato = null;
//			ato = new AffineTransformOp(
//	                   AffineTransform.getScaleInstance((double)width / orgImage.getWidth(), 
//					                                    (double) height / orgImage.getHeight()), 
//					                                    null);
//			ato.filter(orgImage, resizeImage);
			
			resizeImage.getGraphics().drawImage(
	                  orgImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 
	                    0, 0, width, height, null);
	// ここまでリサイズ処理
			ImageOutputStream imageStream = ImageIO.createImageOutputStream(new File(tar));
			ImageWriter writer = null;
			Iterator it = (Iterator) ImageIO.getImageWritersByFormatName("jpg");
			writer = (ImageWriter) it.next();
			writer.setOutput(imageStream);
			JPEGImageWriteParam jpgWriter = new JPEGImageWriteParam(Locale.getDefault());
			jpgWriter.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			jpgWriter.setCompressionQuality(1f);
			writer.write(null, new IIOImage(resizeImage, null, null), jpgWriter);
			imageStream.flush();
			writer.dispose();
			imageStream.close();
			
			return true;
			
			
		}catch(Exception ex){
			System.out.println("[resizeImage]" + ex.getMessage());
			return false;
		}
		
	}
	
}
